import axios from 'axios'
import router from '../router/index'
import { gatewayPrefix, userMiddleContextPath,token, authorization,currentUser} from '@/utils/commConstance'
import {isLogin} from '@/utils/commDataFun'
import { ElMessage } from 'element-plus'
import store from '@/store'

//数据请求字符 boboPlanetMiddleGatewayOutDev
// nginx监听的端口 30008
const BASE_URL = process.env.NODE_ENV !== 'production' ? process.env.VUE_APP_DEV_BASE_URL : process.env.VUE_APP_PROD_SERVER_URL
axios.defaults.baseURL = BASE_URL;
// axios.defaults.baseURL = 'http://localhost:30010/';
// 如果请求超过 `timeout` 的时间，请求将被中断
axios.defaults.timeout = 5000;
// 表示跨域请求时是否需要使用凭证
axios.defaults.withCredentials = false;
// axios.defaults.headers.common['token'] =  '11'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// 允许跨域
axios.defaults.headers.post["Access-Control-Allow-Origin-Type"] = "*";
// 请求拦截器  window.location.href = window.location.origin + '/portal/';
export const $http = axios.create({});
//请求拦截器
const loginUrl = "/gateway/out/boboPlanetUserMiddleDev/userOperation/planetLogin"
$http.interceptors.request.use(
    function(config){
        //弃用
        //const sign = store.state.userSign
        config.headers[token] = sessionStorage.getItem(token)
        config.headers[authorization] = sessionStorage.getItem(authorization)
        return config;
    },
    function(error){
        // message.error('请求超时,请重新登录!!!');
        return Promise.reject(error);
    }
);

// 响应拦截器
$http.interceptors.response.use(
    resp => { 
        if(resp.data.success){
            return resp.data.data
        }else{
            console.log('response result fail ==>',resp);
            if(resp.status === 203){
                loginOut()
                alert("登录已过期，请重新登录");
                router.push('/userLogin')
            }else{
                ElMessage.error(resp.data.msg || '请求失败,请联系管理员')
            }
            
        }    
    },
    err => {
        console.log('axios response error==> ',err);
        try {
            //异常枚举
            if(JSON.stringify(err).indexOf('Network Error') !== -1){
                ElMessage.error('系统异常,请联系管理员！！！')
            }
            if(err.response.status === 203){
                loginOut()
                alert("登录已过期，请重新登录");
                router.push('/userLogin')
            }
            if(err.response.data.msg){
                ElMessage.error(err.response.data.msg)
            }else if(err.response.data.message){
                ElMessage.error(err.response.data.message)
            }else{
                ElMessage.error('系统异常,请联系管理员！！！')
            }
            return Promise.reject(err.response.data.msg || err.response.data.message || '系统异常,请联系管理员!!!')
        } catch (e) {
            return Promise.reject(err);
        }
    }
);

let loginOut = ()=>{
    let user = JSON.parse(sessionStorage.getItem(currentUser))
    $http.get(`${gatewayPrefix}/${userMiddleContextPath}/userOperation/planetUserLogout?account=${user.loginAccount}`).then((res)=>{
        
    }).catch((err)=>{
        console.log('退出登录失败：',err);
    })
    sessionStorage.clear()
}


